//package ai.rpc.core.proxy;
//
//import ai.rpc.core.RpcApplication;
//import ai.rpc.core.config.RpcConfig;
//import ai.rpc.core.constant.RpcConstant;
//import ai.rpc.core.model.RpcRequest;
//import ai.rpc.core.model.RpcResponse;
//import ai.rpc.core.model.ServiceMetaInfo;
//import ai.rpc.core.registry.Registry;
//import ai.rpc.core.registry.RegistryFactory;
//import ai.rpc.core.serializer.JdkSerializer;
//import ai.rpc.core.serializer.Serializer;
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.http.HttpRequest;
//import cn.hutool.http.HttpResponse;
//
//import java.io.IOException;
//import java.lang.reflect.InvocationHandler;
//import java.lang.reflect.Method;
//import java.util.List;
//
///**
// * @Author: mengyu
// * @Date: 2024/7/14
// * 动态代理
// */
//public class ServiceProxyHTTPBAK implements InvocationHandler {
//
//    @Override
//    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        // 指定序列化器
//        Serializer serializer = new JdkSerializer();
//        // 构建 RpcRequest
//        RpcRequest rpcRequest = new RpcRequest();
//        rpcRequest.setServiceName(method.getDeclaringClass().getName());
//        rpcRequest.setMethodName(method.getName());
//        rpcRequest.setParameterTypes(method.getParameterTypes());
//        rpcRequest.setArgs(args);
//
//        // 获取服务地址
//        RpcConfig rpcConfig = RpcApplication.getRpcConfig();
//        Registry registry = RegistryFactory.getInstance(rpcConfig.getRegistryConfig().getRegistry());
//        ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
//        serviceMetaInfo.setServiceName(method.getDeclaringClass().getName());
//        serviceMetaInfo.setServiceVersion(RpcConstant.DEFAULT_SERVICE_VERSION);
//        List<ServiceMetaInfo> serviceMetaInfos = registry.serviceDiscovery(serviceMetaInfo.getServiceKey());
//        if(CollUtil.isEmpty(serviceMetaInfos)){
//            throw new RuntimeException("暂无服务地址");
//        }
//
//        // TODO 服务负载均衡
//        ServiceMetaInfo smi = serviceMetaInfos.get(0);
//
//        // 发送请求
//        String url = smi.getServiceAddress();
//        try {
//            // 序列化
//            byte[] serialize = serializer.serialize(rpcRequest);
//            // 发送
//            try(HttpResponse httpResponse = HttpRequest.post(url)
//                    .body(serialize)
//                    .execute()){
//                byte[] bytes = httpResponse.bodyBytes();
//                // 反序列化
//                RpcResponse deserialize = serializer.deserialize(bytes, RpcResponse.class);
//                return deserialize.getData();
//            }
//
//        }catch (IOException e){
//            e.printStackTrace();
//        }
//        return null;
//    }
//}
